

import { useRuntimeConfig } from '#imports';

export const useApi = async(url, options = {}) => {
  const baseURL = useRuntimeConfig().public.apiBase
  // 默认请求配置
  const defaultOptions = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }

  // 合并请求配置
  const requestOptions = {
    ...defaultOptions,
    ...options,
    headers: {
      ...defaultOptions.headers,
      ...options.headers
    }
  }

  try {
    const { data, error, pending } = await useFetch(url, {
      baseURL,
      method: requestOptions.method,
      body: requestOptions.method !== 'GET' ? requestOptions.body : undefined,
      params: requestOptions.params,
      headers: requestOptions.headers,
      // 响应拦截
      transform: (response) => {
        if (!response) {
          throw createError({
            statusCode: 500,
            message: '服务器响应异常'
          })
        }
        return response
      }
    })

    // 错误处理
    if (error.value) {
      console.error('API Error:', error.value)
      throw createError({
        statusCode: error.value?.statusCode || 500,
        message: error.value?.message || '请求失败'
      })
    }

    return { 
      data: ref(data.value.data), 
      pending,
      error: ref(null)
    }
  } catch (err) {
    return {
      data: ref(null),
      pending: ref(false),
      error: ref(err)
    }
  }
}